package com.sztz.controller;

import com.sztz.oss.BucketTypeEnum;
import com.sztz.oss.minio.MinioTemplate;
import com.sztz.result.BaseResult;
import com.sztz.vo.FileUploadVo;
import com.sztz.vo.FileViewVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件上传下载
 * @author yzy
 * @date 2022/10/19 20:45
 */
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Slf4j
public class FileController {

    private final MinioTemplate minioTemplate;


    /**
     * 文件上传
     * @param fileUploadVo 文件上传参数
     * @author yzy
     * @date 2022/10/31 18:45
     */
    @PostMapping("/upload")
    public BaseResult upload(FileUploadVo fileUploadVo){
        return minioTemplate.putObject(fileUploadVo.getMultipartFile(), BucketTypeEnum.getEnumByBizType(fileUploadVo.getBizType()).getBucketName(), fileUploadVo.getMultipartFile().getOriginalFilename());
    }
    /**
     * 文件上传
     * @param multipartFile 文件上传参数
     * @author yzy
     * @date 2022/10/31 18:45
     */
    @PostMapping("/uploadTest")
    public BaseResult uploadTest(MultipartFile multipartFile, String bizType){
        return minioTemplate.putObject(multipartFile, BucketTypeEnum.getEnumByBizType(bizType).getBucketName(), multipartFile.getOriginalFilename());
    }

    /**
     * 获取文件预览URL
     * @param fileViewVo 请求文件参数
     * @author yzy
     * @date 2022/11/01 16:27
     */
    @PostMapping("/view")
    public BaseResult getViewUrl(@RequestBody FileViewVo fileViewVo){
        return minioTemplate.getObjectUrl(fileViewVo.getBucketName(),fileViewVo.getObjectName(),fileViewVo.getExpire());
    }
    /**
     * 文件下载
     * @param fileViewVo 请求文件参数
     * @author yzy
     * @date 2022/11/01 17:29
     */
    @PostMapping("/download")
    public void download(@RequestBody FileViewVo fileViewVo, HttpServletResponse response){
        minioTemplate.downloadObject(fileViewVo.getBucketName(),fileViewVo.getObjectName(),"jekin.sql",response);
    }
    /**
     * 根据桶名跟文件名删除文件
     * @param fileViewVo 请求文件参数
     * @author yzy
     * @date 2022/11/01 20:05
     */
    @PostMapping("/remove")
    public BaseResult remove(@RequestBody FileViewVo fileViewVo){
        return minioTemplate.removeObject(fileViewVo.getBucketName(),fileViewVo.getObjectName());
    }

}
